package cn.edu.tju.elm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.elm.dto.RefundDto;
import cn.edu.tju.elm.model.Order;
import cn.edu.tju.elm.service.RefundService;

import java.util.List;
import java.util.Map;

/**
 * 退款相关API控制器
 */
@RestController
@RequestMapping("/api/refunds")
public class RefundController {

    @Autowired
    private RefundService refundService;
    
    /**
     * 申请退款
     * @param orderId 订单ID
     * @param requestBody 退款原因和详情
     * @return 处理结果
     */
    @PostMapping("/{orderId}")
    public ResponseEntity<HttpResult> applyRefund(
            @PathVariable Long orderId,
            @RequestBody Map<String, String> requestBody) {
        try {
            String reason = requestBody.getOrDefault("reason", "");
            String detail = requestBody.getOrDefault("detail", "");
            
            if (reason.isEmpty()) {
                return ResponseEntity.badRequest().body(HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "退款原因不能为空"));
            }
            
            Order updatedOrder = refundService.applyRefund(orderId, reason, detail);
            return ResponseEntity.ok(HttpResult.success(updatedOrder));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage()));
        }
    }
    
    /**
     * 商家处理退款申请
     * @param refundId 退款申请ID
     * @param requestBody 处理结果
     * @return 处理结果
     */
    @PostMapping("/{refundId}/process")
    public ResponseEntity<HttpResult> processRefund(
            @PathVariable Long refundId,
            @RequestBody Map<String, Object> requestBody) {
        try {
            Boolean approved = (Boolean) requestBody.getOrDefault("approved", false);
            String rejectReason = (String) requestBody.getOrDefault("rejectReason", "");
            
            Order updatedOrder = refundService.processRefund(refundId, approved, rejectReason);
            return ResponseEntity.ok(HttpResult.success(updatedOrder));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage()));
        }
    }
    
    /**
     * 检查订单是否可以申请退款
     * @param orderId 订单ID
     * @return 检查结果
     */
    @GetMapping("/{orderId}/eligibility")
    public ResponseEntity<HttpResult> checkRefundEligibility(@PathVariable Long orderId) {
        boolean canApply = refundService.canApplyRefund(orderId);
        return ResponseEntity.ok(HttpResult.success(canApply));
    }
    
    /**
     * 获取订单的退款申请
     * @param orderId 订单ID
     * @return 退款申请
     */
    @GetMapping("/order/{orderId}")
    public ResponseEntity<HttpResult> getRefundByOrderId(@PathVariable Long orderId) {
        RefundDto refundDto = refundService.getRefundByOrderId(orderId);
        return ResponseEntity.ok(HttpResult.success(refundDto));
    }
    
    /**
     * 获取商家的所有退款申请
     * @param businessId 商家ID
     * @return 退款申请列表
     */
    @GetMapping("/business/{businessId}")
    public ResponseEntity<HttpResult> getRefundsByBusinessId(@PathVariable Long businessId) {
        List<RefundDto> refunds = refundService.getRefundsByBusinessId(businessId);
        return ResponseEntity.ok(HttpResult.success(refunds));
    }
    
    /**
     * 获取待处理的退款申请
     * @return 退款申请列表
     */
    @GetMapping("/pending")
    public ResponseEntity<HttpResult> getPendingRefunds() {
        List<RefundDto> refunds = refundService.getPendingRefunds();
        return ResponseEntity.ok(HttpResult.success(refunds));
    }

    /**
     * 获取订单的退款详细信息
     * @param orderId 订单ID
     * @return 退款详情
     */
    @GetMapping("/details/order/{orderId}")
    public ResponseEntity<HttpResult> getRefundDetailsByOrderId(@PathVariable Long orderId) {
        try {
            RefundDto refundDto = refundService.getRefundByOrderId(orderId);
            if (refundDto == null) {
                return ResponseEntity.ok(HttpResult.failure(ResultCodeEnum.NOT_FOUND, "未找到此订单的退款记录"));
            }
            return ResponseEntity.ok(HttpResult.success(refundDto));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage()));
        }
    }
} 